<template>
	<view :style="objColor">
		<!--mine/pages/addCar/addCar.wxml-->
		<view class="addCarInfo">
			<template v-if="!isLgxny()">
				<view class="infoItem" @tap="chooseModel">
					<view class="isdisplay">
						<view class="label">爱车车型</view>
						<view class="value">{{
													carTypeText ? carTypeText : "请选择爱车车型"
													}}</view>
					</view>
					<image class="img" src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/back.png"></image>
				</view>
				<view class="infoItem" @tap="opUsePop">
					<view class="isdisplay">
						<view class="label">使用性质</view>
						<view class="value">{{ carNature ? carNature : "请选择使用性质" }}</view>
					</view>
					<image class="img" src="https://oos-cn.ctyunapi.cn/front-end/static/mine/images/back.png"></image>
				</view>
			</template>
			<view class="infoItem">
				<view class="isdisplay">
					<view class="label">
						<view class="xing">*</view>车牌号码
					</view>
					<view class="addree" @tap="showRegionKeyWord">{{ region }}
						<image class="img" src="https://oos-cn.ctyunapi.cn/front-end/static/static/arrow-down-bold.png">
						</image>
					</view>
					<!-- <input type="text" maxlength="7" class="plateNum" :value="plateNo" placeholder="请输入车牌号码" @input="getPlateNo" /> -->
					<view class="addreeplate" @tap="showEn">
						{{plateNo ? plateNo : '请输入车牌号码'}}
						<!-- <input type="text" maxlength="7" class="plateNum" :value="plateNo" placeholder="请输入车牌号码"
							 :disabled="true" /> -->
					</view>
				</view>
			</view>
			<view class="infoItem">
				<view class="isdisplay">
					<view class="label">
						<view class="xing">*</view>车辆类型
					</view>
					<view class="typeItem" v-for="(item,index) in typeList" @tap="checkType" :data-index="index">
						<image class="img"
							:src="typeIndex==index?sellerNo=='jw'?'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkbox_sel-blue.png':'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkRefund_sel.png':'https://oos-cn.ctyunapi.cn/front-end/static/mine/images/checkRefund.png'">
						</image>
						{{ item }}
					</view>
				</view>
			</view>
			<template v-if="!isLgxny()">
				<view class="infoItem">
					<view class="isdisplay">
						<view class="label">续航里程</view>
						<input class="range" type="number" :value="range" placeholder="请输入续航里程" @input="getRange" />
						<view class="unit">公里</view>
					</view>
				</view>
				<!--  <view class="infoItem1">
									<view class="label">车牌识别代号</view>
									<input class="vin1" :value="vin" placeholder="请输入17位的车牌识别代号（VIN)" @input="getVin" />
							</view> -->
				<view class="infoItem">
					<view class="isdisplay">
						<view class="label">我要认证爱车</view>
					</view>
					<u-switch v-model="authorizedFlag" @change="changeSwitch" size="44"></u-switch>
				</view>
			</template>

			<block v-if="authorizedFlag">
				<view class="infoItem2">
					<view class="isdisplay">
						<view class="label">
							<view class="xing">*</view>上传行驶证照片
						</view>
						<!-- <view class="see">查看案例</view> -->
					</view>
					<view class="permit">
						<view class="url-box" v-if="url">
							<image class="icon" :src="url" mode="widthFix" @tap="bindUpload"></image>
							<view class="url-clear" @tap="bindClearUrl">
								<image class="clear-icon"
									src="http://oos-cn.ctyunapi.cn/front-end/static/marketingImg/static/delete_input.png"
									mode="widthFix"></image>
							</view>
						</view>
						<image class="icon"
							src="http://oos-cn.ctyunapi.cn/front-end/static/marketingImg/mine/images/carCard.png"
							mode="widthFix" @tap="bindUpload" v-else></image>
					</view>
				</view>
				<!-- <view class="infoItem">
			        <view class="isdisplay">
			        <view class="label"><view class="xing">*</view>车架号</view>
			        <input class="range" model:value="{{carNo}}" placeholder="请输入车架号" />
			        </view>
			    </view> -->
				<view class="infoItem1">
					<view class="label">
						<view class="xing">*</view>车牌识别代号
					</view>
					<input class="vin1" :value="vin" placeholder="请输入17位的车牌识别代号（VIN)" @input="getVin" />
				</view>
			</block>
		</view>
		<!-- <view class="tips">录入“车辆识别代号”后，可使用车辆“即插即充”服务，插枪
            后直接进入充电，充电成功后自动抵扣余额</view> -->
		<view class="btn" @tap="submitF">提交</view>
		<!-- 地区选择 -->
		<view class="region_warp" :animation="markAnimation">
			<view class="region_list">
				<button v-for="(item,index) in regionArr" :key="index" @tap="setRegion" :data-region="item" class="edit"
					plain="true">
					{{ item }}
				</button>
			</view>
		</view>
		<!-- 键盘 -->
		<view class="keyword-warp" :animation="markAnimationEn">
			<view class="keyword-list" v-for="(item,index) in keyboardArr" :key="index">
				<button v-for="(itemKey,indexKey) in item" :key="indexKey" @tap="setPlateNo" :data-key="itemKey"
					class="edit" plain="true">
					{{ itemKey }}
				</button>
			</view>
		</view>

		<!--使用性质弹窗-->
		<!-- <van-popup show="{{ showUse }}" position='bottom' bind:close="usePopupVisible" data-type="close" custom-class="use_popup">
            <view class="pupBox">
            <view class="tit">使用性质</view>
            <view class="useTitle" wx:for="{{vehicleNatureList}}" wx:key="index" wx:if="{{item.carNatures.length>0}}">{{item.categoryName}}
            <view class="useList">
                <view class="{{car.id==carNatureId?'useItem_sel':'useItem'}}" wx:for="{{item.carNatures}}" wx:for-item="car" wx:key="index" data-name="{{car.carNature}}" data-id="{{car.id}}" bindtap="checkCarNatureId">{{car.carNature}}</view>
            </view>
            </view>
            <view class="btnPup">
            <view class="btn1" bindtap="usePopupVisible">取消</view>
            <view class="btn2" bindtap="enterUsePopupVisible">确定</view>
            </view>
            </view>
        </van-popup> -->
		<uni-popup ref="popup" type="bottom" @close="usePopupVisible">
			<view class="use_popup">
				<view class="pupBox">
					<view class="tit">使用性质</view>
					<view class="useTitle" v-for="(item,index) in vehicleNatureList" :key="index"
						v-if="item.carNatures.length>0">
						{{item.categoryName}}
						<view class="useList">
							<view :class="car.id==carNatureId?'useItem_sel':'useItem'"
								v-for="(car ,carIndx) in item.carNatures" :key="carIndx" :data-name="car.carNature"
								:data-id="car.id" @tap="checkCarNatureId">{{car.carNature}}</view>
						</view>
					</view>
					<view class="btnPup">
						<view class="btn1" @tap="usePopupVisible">取消</view>
						<view class="btn2" @tap="enterUsePopupVisible">确定</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	var app = getApp();
	import {
		vehicleNatureAll,
		addVehicle,
		updateVehicleInfo,
	} from "./../../../api/https";

	export default {
		data() {
			return {
				sellerNo: app.globalData.sellerNo,
				plateNo: "", //车牌号  
				range: "", //续航里程
				vin: "",
				type: "add", //车辆信息类型（add新增，edit修改）
				typeIndex: 0, //默认第一个车辆类型
				vehicleType: "DianDong", //默认车辆类型（纯电动）
				typeList: ["纯电动", "混合电动"], //车辆类型
				markAnimation: null, // mark动画
				markAnimationEn: null,
				showUse: false,
				carNature: "", //车辆性质名称
				carNatureId: 0, //车辆性质id
				carId: 0,
				region: "",
				carTypeText: "", //车型
				vehicleNatureList: [], //车辆性质列表
				regionArr: [
					"京",
					"津",
					"冀",
					"鲁",
					"晋",
					"蒙",
					"辽",
					"吉",
					"黑",
					"苏",
					"浙",
					"皖",
					"闽",
					"赣",
					"豫",
					"鄂",
					"湘",
					"粤",
					"沪",
					"桂",
					"渝",
					"川",
					"贵",
					"云",
					"琼",
					"新",
					"宁",
					"藏",
					"陕",
					"甘",
					"青",
					"关闭",
				],
				keyboardArr: [
					['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],
					['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'],
					['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ],
					['收起', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '删除'],
				],
				authorizedFlag: false,
				url: ''
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			if (options.type == "edit") {
				// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
				let data = {};
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.on('acceptDataFromOpenerPage', (res) => {
					console.log("编辑信息========",res)
					data = res
					uni.setNavigationBarTitle({
						title: "编辑车辆",
					});
					this.setData({
						type: "edit",
						carTypeText: (data.brandName && data.carTypeName) ?
							`${data.brandName}-${data.carTypeName}` : '',
						region: data.plateNo && data.plateNo.slice(0, 1),
						plateNo: data.plateNo && data.plateNo.slice(1),
						vehicleType: data.vehicleType,
						typeIndex: data.vehicleType == "DianDong" ? 0 : 1,
						range: data.mileage,
						vin: data.vin,
						brandId: data.brandId, // 汽车品牌
						carTypeId: data.carTypeId, // 车型
						carNatureId: data.carNatureId,
						carNature: data.carNature && data.carNature.carNature,
						carId: data.id,
						authorizedFlag: data.status == 1 ? true : false,
						url: data.url
					});
				})
			}
		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {
			const chooseCar = uni.getStorageSync('chooseCarInfo')
			if (chooseCar) {
				const {
					carTypeText,
					brandId,
					carTypeId
				} = JSON.parse(chooseCar)
				this.setData({
					carTypeText,
					brandId,
					carTypeId,
				});
			}
			uni.setStorageSync('chooseCarInfo', '')
			// const pages = getCurrentPages();
			// const currPage = pages[pages.length - 1];
			// if(currPage.data) {
			//     this.setData({
			//     carTypeText: currPage.data.carTypeText,
			//     brandId: currPage.data.brandId, // 汽车品牌id
			//     carTypeId: currPage.data.carTypeId, // 车辆型号id
			// });
			// }
			// this.setData({
			//   carTypeText: app.globalData.bindCarDetailsCarDetails.carTypeText,
			// })
			// if(this.type=="add"){
			//   this.setData({
			//   brandId: app.globalData.bindCarDetails.brandId, // 汽车品牌id
			//   carTypeId: app.globalData.bindCarDetails.carTypeId, // 车辆型号id
			//   })
			// }
			this.vehicleNatureAll();
		},

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			this.setData({
				carTypeText: "",
			});
		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage() {},
		methods: {
			//查询车辆性质列表
			vehicleNatureAll() {
				vehicleNatureAll().then((res) => {
					if (res.code == 0) {
						this.setData({
							vehicleNatureList: res.data,
						});
						//   if(this.carNatureId){
						//     console.log("打印",this.carNatureId)
						//   let list=res.data
						//   list.forEach((element:any) => {
						//   if(this.carNatureId==element.id){
						//     this.setData({
						//       carNature: element.carNature
						//     })
						//   }
						//   });
						// }
					}
				});
			},
			//选择性质
			checkCarNatureId(e) {
				let id = e.currentTarget.dataset.id;
				let name = e.currentTarget.dataset.name;
				this.setData({
					carNatureId: id,
					carNature: name,
				});
			},
			//确定性质
			enterUsePopupVisible() {
				// this.setData({
				//     showUse: false,
				// });
				this.$refs.popup.close()
			},
			//选择车型
			chooseModel: function() {
				uni.navigateTo({
					url: "../chooseCarModel/chooseCarModel",
				});
			},
			// showUse() {
			//     this.setData({
			//         showUse: true
			//     })
			opUsePop() {
				this.$refs.popup.open()
			},
			usePopupVisible() {
				this.setData({
					carNatureId: 0,
					carNature: "",
					// showUse: false,
				});
				this.$refs.popup.close()
			},
			//车牌号
			getPlateNo: function(e) {
				this.setData({
					plateNo: e.detail.value,
				});
			},
			//续航里程
			getRange: function(e) {
				this.setData({
					range: e.detail.value,
				});
			},
			//vin
			getVin: function(e) {
				this.vin = e.detail.value
			},
			changeSwitch(e) {
				this.authorizedFlag = e
			},
			bindUpload() {
				const that = this;
				wx.chooseImage({
					success(res) {
						const tempFilePaths = res.tempFilePaths
						wx.uploadFile({
							url: getApp().globalData.URL + '/member-service/common/upload', //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'user': 'test'
							},
							success(rest) {
								const data = JSON.parse(rest.data)
								console.log(data, '-----data------', data.code, data.data)
								if (data.code == 0) {
									that.url = data.data
								}
							}
						})
					}
				})
			},
			bindClearUrl() {
				this.url = ''
			},
			//选择车辆类型
			checkType(e) {
				let index = e.currentTarget.dataset.index;
				this.setData({
					typeIndex: index,
				});
				if (index == 0) {
					this.setData({
						vehicleType: "DianDong",
					});
				} else {
					this.setData({
						vehicleType: "HunHeDongLi",
					});
				}
			},
			hideKeyword() {
				uni.hideKeyboard();
				console.log('隐藏键盘')
			},
			showRegionKeyWord() {
				console.log("-----showRegionKeyWord------")
				this.showEnKeyword("", "-470rpx");
				this.showRegion()
			},
			showEn() {
				console.log("-----showEn------")
				this.showRegion("", "-470rpx");
				this.showEnKeyword()
			},
			// 选择地区简称
			setRegion: function(e) {
				const region =
					e.target.dataset.region == "关闭" ?
					this.region :
					e.target.dataset.region;
				this.setData({
					region,
				});
				this.showRegion("", "-470rpx");
			},
			// 键盘显示
			showRegion: function(e, bottom = "0") {
				// console.log(this.markAnimationEn)
				var markAnimation = uni.createAnimation({
					duration: 500, //  动画持续多少毫秒
					timingFunction: "ease", // “运动”的方式，例子中的 'linear'代表匀速
					delay: 10, // 多久后动画开始运行
				});
				markAnimation.bottom(bottom).step();
				this.setData({
					markAnimation: markAnimation.export(),
				});
			},
			setPlateNo(e) {
				const value = e.target.dataset.key
				if (value === '收起') {
					this.showEnKeyword("", "-470rpx");
				} else if (value === '删除') {
					if (this.plateNo.length > 0) {
						this.plateNo = this.plateNo.slice(0, this.plateNo.length - 1)
					}
				} else {
					if (this.plateNo.length < 7) {
						this.plateNo = `${this.plateNo}${value}`
					}

				}


			},
			// 英文键盘
			showEnKeyword: function(e, bottom = "0") {
				var markAnimationEn = uni.createAnimation({
					duration: 500, //  动画持续多少毫秒
					timingFunction: "ease", // “运动”的方式，例子中的 'linear'代表匀速
					delay: 10, // 多久后动画开始运行
				});
				markAnimationEn.bottom(bottom).step();
				this.setData({
					markAnimationEn: markAnimationEn.export(),
				});
			},
			tips(msg) {
				uni.showToast({
					title: msg,
					icon: "none",
					duration: 2000,
				});
			},
			// 提交
			submitF: function() {
				var regRule = /[~#^$@%&!*()<>:;'"{}【】 	]/gi;
				// if (!app.globalData.bindCarDetails.brandId&&this.type=='add') {
				//   console.log(this.type,"打印",app.globalData.bindCarDetails,!app.globalData.bindCarDetails.brandId&&this.type=='add')
				//   this.tips('请选择汽车品牌')
				//   return
				// }
				// if (!this.brandId) {
				// 	this.tips("请选择汽车品牌");
				// 	return;
				// }
				// if (!app.globalData.bindCarDetails.carTypeId&&this.type=='add') {
				//   this.tips('请选择车辆型号')
				//   return
				// }
				// if (!this.carTypeId) {
				// 	this.tips("请选择汽车品牌");
				// 	return;
				// }
				// if (!this.carNatureId) {
				//   this.tips('请选择车辆性质')
				//   return
				// }
				if (regRule.test(this.plateNo)) {
					this.tips("请输入正确车牌号");
					return;
				}
				if (this.region == "" || this.plateNo == "" || this.plateNo.length < 6) {
					this.tips("请输入正确车牌号");
					return;
				}
				// if (regRule.test(this.vin)) {
				// 	this.tips("请输入正确Vin");
				// 	return;
				// }
				if (this.authorizedFlag) {
					if (!this.url) {
						this.tips('请上传行驶证照片')
						return
					}
					if (regRule.test(this.vin)) {
						this.tips('请输入正确Vin')
						return
					}
				}
				const data = {
					plateNo: `${this.region}${this.plateNo}`, // 车牌号
					brandId: this.brandId, // 汽车品牌id
					carTypeId: this.carTypeId, // 车辆型号id
					carNatureId: this.carNatureId, //车辆性质id
					mileage: this.range, // 续航里程
					vehicleType: this.vehicleType, // 车辆类型
					vin: this.vin, // 车辆自编号
					authorizedFlag: this.authorizedFlag, //是否认证
					url: this.url, //行驶证照片
				};
				if (this.type == "edit") {
					updateVehicleInfo({
						...data,
						id: this.carId,
					}).then((res) => {
						if (res.code == 0) {
							uni.showToast({
								title: "成功",
								icon: "success",
								duration: 2000,
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 2000);
							// wx.showModal({
							//   title: '提示',
							//   content: '修改车辆信息成功',
							//   confirmText: '车辆列表',
							//   success(res) {
							//     if (res.confirm) {
							//       wx.navigateBack()
							//     }
							//   }
							// })
						} else {
							// app.globalData.bindCarDetails = {}
							this.tips(res.msg);
						}
					});
				} else {
					addVehicle({
						...data,
					}).then((res) => {
						if (res.code == 0) {
							uni.showToast({
								title: "成功",
								icon: "success",
								duration: 2000,
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 2000);
							// wx.showModal({
							//   title: '提示',
							//   content: '添加车辆成功',
							//   confirmText: '车辆列表',
							//   success(res) {
							//     if (res.confirm) {
							//       wx.navigateBack()
							//     }
							//   }
							// })
						} else {
							// app.globalData.bindCarDetails = {}
							this.tips(res.msg);
						}
					});
				}
			},
		},
	};
</script>
<style lang="less">
	@import url("./addCar.less");
</style>